import { fetchEnterpriseListAPI, deleteEnterpriseAPI, uploadAPI, fetchIndustryListAPI, findEnterpriseAPI, addEnterpriseAPI, editEnterpriseAPI, fetchCurrentContractAPI, deleteContractAPI, rentingQutAPI } from '@/api/park/enterpriseApi'

const actions = {
  /* 发送请求获取企业的action */
  async fetchEnterpriseList(context, pageParams) {
    const { data: enterpriseListInfo } = await fetchEnterpriseListAPI(pageParams)
    enterpriseListInfo.rows.forEach(item => item.list = [])
    context.commit('updateEnterpriseList', enterpriseListInfo)
  },
  /* 发送请求删除企业的action */
  async deleteEnterprise(context, enterpriseId) {
    await deleteEnterpriseAPI(enterpriseId)
    return '删除企业成功'
  },
  /* 发送请求查找企业的action */
  async findEnterprise(context, enterpriseId) {
    const { data } = await findEnterpriseAPI(enterpriseId)
    return data
  },
  /* 发送请求添加企业的action */
  async addEnterprise(context, data) {
    await addEnterpriseAPI(data)
    return '添加企业成功'
  },
  /* 发送请求编辑企业的action */
  async editEnterprise(context, data) {
    await editEnterpriseAPI(data)
    return '编辑企业成功'
  },
  /* 发送请求获取当前企业下租赁列表的action */
  async fetchCurrentContract(context, id) {
    const { data: contractList } = await fetchCurrentContractAPI(id)
    context.commit('updateCurrentContract', { contractList, id })
  },
  /* 发送请求退租租赁列表的action */
  async rentingQut(context, id) {
    await rentingQutAPI(id)
    return '退租成功'
  },
  /* 发送请求删除企业租赁合同的action */
  async deleteContract(context, id) {
    await deleteContractAPI(id)
    return '删除合同成功'
  },
  /* 发生请求上传企业营业执照的action */
  async upload(context, formData) {
    const { data } = await uploadAPI(formData)
    return data
  },
  /* 发送请求查询企业所属行业列表的action */
  async fetchIndustryList(context) {
    const { data } = await fetchIndustryListAPI()
    context.commit('updateIndustryList', data)
  }
}
const mutations = {
  /* 更新企业列表的mutation */
  updateEnterpriseList(state, enterpriseListInfo) {
    state.enterpriseListInfo = enterpriseListInfo
  },
  /* 更新企业所属行业列表的mutation */
  updateIndustryList(state, industryList) {
    state.industryList = industryList
  },
  /* 更新当前企业租赁列表的mutation */
  updateCurrentContract(state, { contractList, id }) {
    const currentEnterprise = state.enterpriseListInfo.rows.find(item => item.id === id)
    currentEnterprise.list = contractList
  }
}
const state = () => {
  return {
    enterpriseListInfo: {},
    industryList: []
  }
}

const getters = {
  total: state => state.enterpriseListInfo.total,
  enterpriseList: state => state.enterpriseListInfo.rows
}

export default {
  actions,
  mutations,
  state,
  getters,
  namespaced: true
}
